package org.ratingviewer.data.source;

import java.io.*;
import java.text.MessageFormat;

import org.apache.commons.io.*;
import org.apache.http.protocol.HTTP;
import org.htmlparser.lexer.Page;
import org.ratingviewer.data.PageGetException;

public class LocalDataSource implements DataSource {

	private static final String PAGE_SUFFIX = ".html";

	private static final String PAGE_RATING_NAME = "reiting";
	private static final String PAGE_PLAYER_PROFILE_NAME = "profile";
	private static final String PAGE_GAMES_NAME = "games";
	private static final String PAGE_GAME_NAME = "game-view";

	private final File sourceRoot;
	private final String charSet;

	public LocalDataSource(File sourceRoot, String charSet) {
		super();

		if (sourceRoot == null)
			throw new IllegalArgumentException("Source root folder can't be null.");
		this.sourceRoot = sourceRoot;

		if (charSet == null)
			charSet = HTTP.ISO_8859_1;
		this.charSet = charSet;
	}

	public File getSourceRoot() {
		return sourceRoot;
	}

	@Override
	public Page findPlayer(String caseSensitiveName) throws PageGetException {
		String pageContent = getPageContent(PAGE_RATING_NAME, charSet);
		return new Page(pageContent, charSet);
	}

	private String getPageContent(String pageName, String charSet) throws PageGetException {
		File pageFile = new File(sourceRoot, pageName + PAGE_SUFFIX);
		if (!pageFile.exists() || !pageFile.canRead())
			throw new PageGetException(MessageFormat.format("Page file ''{0}'' can''t be readed.",
					pageFile.getName()));

		FileInputStream pageIn = null;
		try {
			pageIn = FileUtils.openInputStream(pageFile);
			StringWriter contentWriter = new StringWriter();
			IOUtils.copy(pageIn, contentWriter, charSet);
			return contentWriter.toString();
		} catch (IOException ex) {
			throw new PageGetException(MessageFormat.format("IO error occurred on page file read: {0}",
					ex.getLocalizedMessage()), ex);
		} finally {
			IOUtils.closeQuietly(pageIn);
		}
	}
}
